package com.hantang.web.json.handlers;

import java.util.Date;

import org.apache.log4j.Logger;
import org.glassfish.grizzly.http.server.Request;
import org.glassfish.grizzly.http.server.Response;

import com.google.gson.Gson;
import com.hantang.web.dao.ArticleDao;
import com.hantang.web.data.ArticleData;
import com.hantang.web.json.ds.MetaData;
import com.hantang.web.json.res.StringRes;

public class EditArticleHandler extends AbstractHandler {

	private static Logger logger = Logger.getLogger(EditArticleHandler.class);
	@Override
	public String doService(Request req, Response resp) throws Exception {
		String id = req.getParameter("id");
		String username = req.getParameter("username");
		String category = req.getParameter("category");
		String title = req.getParameter("title");
		String keyWords = req.getParameter("keyWords");
		String content = req.getParameter("content");
		
		String sret = handleServlet(id, username, category, title, keyWords,
				content);
		
		return sret;
	}

	public static String handleServlet(String id, String username, String category,
			String title, String keyWords, String content) {
		StringRes res = new StringRes();
		if(id != null){
			ArticleData adata = new ArticleData();
			adata.setId(Long.valueOf(id));
			adata.setAuthor(username);
			adata.setCategory(category);
			adata.setContent(content);
			adata.setKeyWords(keyWords);
			adata.setTitle(title);
			adata.setUpdateTime(new Date());
			adata.setPublishTime(null);
			adata.setRemarks(null);
			
			boolean isOk = handle(adata);
			if(isOk){
				res.setData(adata.getId() + "");
				res.setMeta(new MetaData(MetaData.META_DATA_SUCCESS_CODE,"Succ"));
			}else{
				res.setMeta(new MetaData(MetaData.META_DATA_FAILED_CODE,"Failed"));
			}
		}else{
			res.setMeta(new MetaData(MetaData.META_DATA_ERROR_PARA,"para id is null."));
			logger.error("para id is null.");
		}
		
		String sret = new Gson().toJson(res);
		return sret;
	}

	public static boolean handle(ArticleData data)
	{
		if(data == null){
			return false;
		}
		boolean isOk = false;
		
		ArticleDao dao = new ArticleDao();
		isOk = dao.updateData(data);
		if(isOk)
		{
			isOk = true;
			logger.info("handle, updateData Succ! ");
		}else{
			logger.error("handle, updateData Failed! data:" + data.toString());
		}
		return isOk;
	}
}
